package YAVMM::GuestManager::Plugin::Libvirt;
use Moose::Role;

use TryCatch;
use Sys::Virt;

use YAVMM::Error::Guest::Libvirt;

has 'vmm' => (
    is         => 'rw',
    isa        => 'Sys::Virt',
    lazy_build => 1,
);

sub start_guest {
    my $self  = shift;
    my $guest = shift; # YAVMM::Guest

    try {
	$self->vmm->create_domain($self->_guest_to_xml($guest));
    } catch (Sys::Virt:Error $err) {
	die YAVMM::Error::Guest::Libvirt($err);
    }
}

sub stop_guest {
    my $self  = shift;
    my $guest = shift;

    my $running_guest;

    try {
	$running_guest = $self->vmm->get_domain_by_name($guest->name);
	# die if $running_guest is not defined?
	if ($running_guest->is_active) {
	    $running_guset->shutdown();
	}
    } catch (Sys::Virt:Error $err) {
	die YAVMM::Error::Guest::Libvirt($err);
    }
}

sub kill_guest {
    my $self  = shift;
    my $guest = shift;

    my $running_guest;

    try {
	$running_guest = $self->vmm->get_domain_by_name($guest->name);
	# die if $running_guest is not defined?
	if ($running_guest->is_active) {
	    $running_guset->destroy();
	}
    } catch (Sys::Virt:Error $err) {
	die YAVMM::Error::Guest::Libvirt($err);
    }
}

sub migrate_guest {
    my $self     = shift;
    my $guest    = shift;
    my $dst_host = shift;

    try {
	my $running_guest = $self->vmm->get_domain_by_name($guest->name);
	$running_guest->migrate_to_uri(
	    "qemu://$dst_host/system",
	    Sys::Virt::Domain::MIGRATE_LIVE,
	);
    } catch (Sys::Virt::Error $err) {
	die YAVMM::Error::Guest::Libvirt($err);
    }
}

sub get_guest_console_info {
    my $self  = shift;
    my $guest = shift; # YAVMM::Guest
}

sub _build_vmm {
    my $self = shift;

    my $uri = 'qemu:///system';

    my $vmm;
    try {
	$vmm = Sys::Virt->new(
	    address => $uri,
	);
    } catch (Sys::Virt::Error $e) {
    }

    return $vmm;
}

sub _guest_to_xml {
    my $self  = shift;
    my $guest = shift;
}

1;

__END__
